<!--
  * 采退单表单
  *
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <!---------- 基本信息 begin ----------->
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="仓库" name="warehouse_id">
              <Select name="Warehouse" :fetch-params="selectFetchParams.warehouse" v-model:value="form.warehouse_id" placeholder="请选择仓库" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="供应商" name="supplier_id">
              <Select name="Supplier" v-model:value="form.supplier_id" placeholder="请选择供应商" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="备注">
              <a-input v-model:value="form.remark" placeholder="请输入整单备注" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <!---------- 基本信息 end ----------->
      <!---------- 商品信息 begin ----------->
      <a-card title="商品信息" class="smart-margin-bottom10">
        <a-table size="small" :dataSource="form.detail" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false">
          <template #bodyCell="{ text, record, column, index }">
            <template v-if="column.dataIndex === 'index'">
              <div class="form-table-index">
                <span>{{ index + 1 }}</span>
                <div class="form-table-index-btn-wrap">
                  <div class="form-table-index-btn">
                    <div class="form-table-index-btn-item" @click="addFormDetail(index)">+</div>
                    <div class="form-table-index-btn-item" @click="delFormDetail(index)">-</div>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'goods_name'">
              <a-form-item class="form-table-item" required :name="['detail', index, 'goods_name']" :rules="[{ required: true, message: '请添加商品' }]">
                <!-- 使用 a-tooltip 显示-->
                <a-tooltip v-if="text">
                  <template #title>{{ text }}</template>
                  <a-input :value="text" readonly placeholder="请输入商品名称" size="small">
                    <template #suffix>
                      <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                    </template>
                  </a-input>
                </a-tooltip>
                <a-input :value="text" readonly placeholder="请输入商品名称" size="small" v-else>
                  <template #suffix>
                    <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                  </template>
                </a-input>
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'img'">
              <a-image :width="text ? 30 : 50" :src="record.goods_name ? text || failImg : ''" />
            </template>
            <template v-if="column.dataIndex === 'quantity'">
              <a-form-item class="form-table-item">
                <a-input-number v-model:value="record.quantity" :min="1" @blur="validateQuantity(record)" />
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'purchase_price'">
              <a-form-item class="form-table-item">
                <a-input-number v-model:value="record.purchase_price" :min="0" />
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'purchase_total_price'">
              {{ _.multiply(record?.quantity ?? 0, record?.purchase_price ?? 0).toFixed(2) }}
            </template>
            <template v-if="column.dataIndex === 'remark'">
              <a-form-item class="form-table-item">
                <a-input v-model:value="record.remark" />
              </a-form-item>
            </template>
          </template>
        </a-table>
      </a-card>
      <!---------- 商品信息 end ----------->
    </a-form>
    <GoodsSelectModal ref="goodsSelectModalRef" checkStock :type="1" :is_sold="1" @confirm="onSelectGoods" />
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { ref, nextTick, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import _ from 'lodash'
import { errorSentry } from '@/lib/error-sentry'
import Select from '@/components/business/select/index.vue'
import GoodsSelectModal from '@/components/business/goods-select-modal/index.vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { withdrawalApi } from '@/api/business/orders/withdrawal-api'
import { ORDER_TYPE_ENUM } from '@/constants/business/orders-const'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import failImg from '@/assets/images/notice/failImg.png'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reloadList'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 供应商ID
  supplier_id: undefined,
  // 仓库ID
  warehouse_id: undefined,
  // 整单备注
  remark: '',
  // 订单类型
  type: ORDER_TYPE_ENUM.WITHDRAWAL,
  // 商品数据
  detail: []
}
const form = ref({ ...formDefault })
onMounted(() => form.value.detail.push({}))
const rules = {
  warehouse_id: [{ required: true, message: '请选择仓库' }],
  supplier_id: [{ required: true, message: '请选择供应商' }]
}
// 是否展示抽屉
const visible = ref(false)
// 商品数量验证
const validateQuantity = (record) => {
  // 检查是否为正整数
  if (!Number.isInteger(record.quantity) || record.quantity <= 0) {
    message.error('请输入正整数')
    record.quantity = 1 // 重置为默认值
  }
}

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData.id && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    if (form.value.id) {
      // 加载商品详情数据
      form.value.detail = rowData.detail.map((item) => {
        return {
          ...item,
          goods_name: item?.goods?.goods_name,
          img: item?.goods?.img,
          unit: item?.spec?.unit_name,
          barcode: item?.spec?.barcode,
          spec_name: item?.spec?.spec_name,
          quantity: item.quantity, // 数量
          purchase_price: item.purchase_price, // 单价
          remark: item.remark // 备注
        }
      })
      form.value.detail.push({})
    }
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  deletedGoods.value = []
  visible.value = false
}

async function onSubmit() {
  const validItems = unref(form).detail.filter((item) => !_.isEmpty(item) && item.quantity !== 0)
  if (validItems.length === 0) {
    message.error('请选择商品')
    return
  }
  form.value.detail = validItems
  await nextTick()
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          const keys = ['id', 'quantity', 'purchase_price', 'goods_id', 'goods_spec_id', 'purchase_total_price', 'remark']
          unref(form).detail.forEach((item) => {
            item.purchase_total_price = _.floor(_.multiply(item.quantity, item.purchase_price), 2)
          })
          const specData = _(unref(form).detail)
            .concat(deletedGoods.value)
            .cloneDeep()
            .map((item) => {
              const result = _.pick(item, keys)
              if (deletedGoods.value.some((good) => good.id === item.id)) {
                result.is_delete = 1
              }
              return result
            })
          const data = {
            ...unref(form),
            detail: JSON.stringify(specData),
            type: 2
          }
          await withdrawalApi.edit(data)
        } else {
          const keys = ['quantity', 'purchase_price', 'goods_id', 'goods_spec_id', 'purchase_total_price', 'remark']
          unref(form).detail.forEach((item) => {
            item.purchase_total_price = _.floor(_.multiply(item.quantity, item.purchase_price), 2)
          })
          const specData = _(unref(form).detail)
            .cloneDeep()
            .map((item) => _.pick(item, keys))
          const data = {
            ...unref(form),
            detail: JSON.stringify(specData),
            type: 2
          }
          await withdrawalApi.create(data)
        }
        message.success('操作成功')
        onClose()
        emit('reloadList')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 商品选择弹窗
const goodsSelectModalRef = ref()
const modalIndex = ref(0)
// 记录点击多选按钮的表格行索引，插入数据时使用
function showGoodsSelectModal(index: number) {
  if (!form.value.warehouse_id) {
    message.error('仓库ID未加载完成，请稍后再试')
    return
  }
  modalIndex.value = index
  goodsSelectModalRef.value.showModal({ warehouse_id: form.value.warehouse_id })
}

// 记录已删除的商品
const deletedGoods = ref([])

// 商品选择回调
function onSelectGoods(goodsList) {
  // 处理商品数据
  function handleGoodsData(rowData) {
    const keys = ['goods_name', 'img', 'no', 'unit', 'spec']
    const specData = _.find(rowData.spec, (item) => item.unit_type === rowData.default_unit_type)
    return {
      ..._.pick(rowData, keys),
      barcode: specData.barcode,
      spec_name: specData.spec_name,
      unit: specData.unit_name,
      spec_sale_price: specData.sale_price,
      goods_id: specData.goods_id,
      goods_spec_id: specData.id,
      quantity: Number(specData.min_quantity),
      purchase_price: Number(specData.sale_price),
      remark: ''
    }
  }
  // 如果当前索引值有数据则覆盖
  const rows = _.map(goodsList, handleGoodsData)
  if (unref(form).detail[modalIndex.value]) {
    if (unref(form).detail[modalIndex.value].id) {
      deletedGoods.value.push(form.value.detail[modalIndex.value])
    }
    form.value.detail.splice(modalIndex.value, 1, ...rows)
  } else {
    // 否则插入数据
    if (modalIndex.value === 0) {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value, 0, ...rows)
    } else {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value + 1, 0, ...rows)
    }
  }
  // 自动追加一个空行
  if (!_.isEmpty(_.last(unref(form).detail))) form.value.detail.push({})
}

// ----------------------------------  商品信息  ----------------------------------
// 表头配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: 260
  },
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '规格条码',
    dataIndex: 'barcode'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    width: 120
  },
  {
    title: '采退单价',
    dataIndex: 'purchase_price',
    width: 120
  },
  {
    title: '小计',
    dataIndex: 'purchase_total_price'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  }
]

// 增加空行
function addFormDetail(index: number) {
  form.value.detail.splice(index + 1, 0, {})
}
// 删除行
function delFormDetail(index: number) {
  const formDetail = unref(form).detail // 获取当前的详情数组
  const item = formDetail[index] // 获取要删除的项

  // 检查是否只剩最后一条数据
  if (formDetail.length === 1) {
    message.error('不能删除最后一条数据！') // 提示用户
    return // 退出函数，不执行后续操作
  }

  // 如果是编辑状态，将删除的项加入已删除列表
  if (unref(form).id && item.id) {
    deletedGoods.value.push(item)
  }

  // 删除指定索引的元素
  formDetail.splice(index, 1)
}
// function delFormDetail(index: number) {
//   const item = unref(form).detail[index]
//   if (unref(form).id && item.id) {
//     // 如果是编辑状态
//     deletedGoods.value.push(item)
//   }
//   unref(form).detail.splice(index, 1) // 如果是新增状态，直接移除
// }

// 仓库查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.EXPIRED.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询']
    },
    fields: 'id,name'
  }
}

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新建'))
</script>
<style scoped lang="less">
.form-table-item {
  margin-bottom: 0;
  max-width: 200px;
}
.form-table-index {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  .form-table-index-btn-wrap {
    display: none;
  }
  .form-table-index-btn {
    display: flex;
  }
  .form-table-index-btn-item {
    width: 50%;
    height: 100%;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .form-table-index-btn-item:hover {
    background: #f87171ff;
    color: white;
  }
}
.form-table-index:hover span {
  display: none;
}
.form-table-index:hover .form-table-index-btn-wrap {
  display: block;
}
</style>
